package com.rk.kbk.controller;

import com.rk.kbk.common.JsonResp;
import com.rk.kbk.common.Md5;
import com.rk.kbk.dao.AdminAuthorityDao;
import com.rk.kbk.dao.AdminCatalogDao;
import com.rk.kbk.dao.AdminDao;
import com.rk.kbk.dto.PageDto;
import com.rk.kbk.model.Admin;
import com.rk.kbk.model.AdminAuthority;
import com.rk.kbk.model.AdminCatalog;
import com.rk.kbk.service.AdminService;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import java.io.UnsupportedEncodingException;
import java.util.*;


/**
 * @AdminController
 * @管理员Controller
 * @version : Ver 1.0
 */
@CrossOrigin
@RestController
@Transactional
@RequestMapping(value="/api/admin")
public class AdminController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private AdminDao adminDao;
    @PersistenceContext
    private EntityManager entityManager;
    @Autowired
    private AdminAuthorityDao adminAuthorityDao;
    @Autowired
    private AdminService adminService;
    @Autowired
    private AdminCatalogDao adminCatalogDao;

    /**
     * 登录  后台
     *
     * @return JsonResp
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "/login",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp login(@RequestBody Admin admin) {
        log.debug("登录");
        String userName=admin.getUserName();
        String password=admin.getPassword();
        return adminService.login(userName, password);
    }

    /**
     * 注销
     */
    @RequestMapping(value = "/logout",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp logout(){
        log.debug("注销");
        adminService.logout();
        return JsonResp.ok();
    }

    /**
     * 权限
     *
     * @return JsonResp
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "/getJurisdiction",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp login() {
        Admin admin = adminService.currentUser();
        List<Map<String,Object>> list = new ArrayList<>();
        if (admin.getRoleType()==2) {   //管理员
            List<AdminAuthority> adminAuthorityList=adminAuthorityDao.findByAdminIdAndStatus(admin.getId(),1);
            for (AdminAuthority adminAuthority : adminAuthorityList) {
                Map<String, Object> map = new HashMap<>();
                //一级目录
                AdminCatalog one = adminCatalogDao.findOne(adminAuthority.getCatalogId());
                //二级目录
                List<AdminCatalog> two = adminCatalogDao.findByParentIdAndStatus(one.getId(),1);
                map.put("one", one);
                map.put("two", two);
                list.add(map);
            }
        }else { //超级管理员
            //一级目录
            List<AdminCatalog> adminCatalogs=adminCatalogDao.findByStatusAndParentIdIsNull(1);
            for (AdminCatalog adminCatalog:adminCatalogs ) {
                Map<String, Object> map = new HashMap<>();
                //二级目录
                List<AdminCatalog> two = adminCatalogDao.findByParentIdAndStatus(adminCatalog.getId(),1);
                map.put("one", adminCatalog);
                map.put("two", two);
                list.add(map);
            }
        }
        return JsonResp.ok(list);
    }


    /**
     * @添加/修改管理员
     * @param
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/addAdmin",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp addAdmin(String userName,String nick,String password,String realName,String catalogIds){
        log.debug("添加管理员和对应得权限目录列表");
        //判断是否是超级管理员
        Admin currentUser = adminService.currentUser();
        if(currentUser.getRoleType() != 1){
            return JsonResp.fa("无权操作！");
        }
        Admin admin=new Admin();
        admin.setUserName(userName);//账号
        admin.setPassword(Md5.md5Encode(password));
        admin.setRealName(realName);
        admin.setNickName(nick);
        admin.setStatus(1);
        admin.setRoleType(2);//默认为普通管理员
        adminDao.save(admin);
        Long adminId=admin.getId();
       //设置该管理员对应的权限目录列表
        List<String> catalogIdList= Arrays.asList(catalogIds.split(","));
        List<AdminAuthority> adminAuthorityList=new ArrayList<>();
         for(String str:catalogIdList){
             AdminAuthority adminAuthority=new AdminAuthority();
             adminAuthority.setAdminId(adminId);
             adminAuthority.setCatalogId(Long.valueOf(str));
             adminAuthority.setStatus(1);
             adminAuthorityList.add(adminAuthority);
         }
        adminAuthorityDao.save(adminAuthorityList);
        return JsonResp.ok();
    }

    /**
     * @批量添加/修改管理员
     * @param admins
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/addOrUpdateSomeAdmin",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp addOrUpdateSomeAdmin(@RequestBody List<Admin> admins){
        log.debug("批量添加/修改管理员");
        adminDao.save(admins);
        return JsonResp.ok();
    }

    /**
     * @获取管理员详情-ByAdminId
     * @param adminId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/adminDetails",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findAdminDetailsByAdminId(Long adminId) {
        log.debug("获取管理员详情-ByAdminId");
        return JsonResp.ok(adminDao.findOne(adminId));
    }

    /**
     * @获取管理员详情
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/getadmin",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findAdminDetails() {
        log.debug("获取管理员详情");
        return JsonResp.ok(adminService.currentUser());
    }

    /**
     * @修改密码 根据id
     * @param adminId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/updatePassword",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp updatePassword(Long adminId) {
        log.debug("获取管理员详情-ByAdminId");
        Admin admin=adminDao.findOne(adminId);
        admin.setPassword(Md5.md5Encode("123456"));//默认密码
        adminDao.save(admin);
        return JsonResp.ok();
    }


    /**
     * @删除管理员 根据id
     * @param id
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/deleteAdmin",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp deleteAdmin(Long id) {
        log.debug("获取管理员详情-ByAdminId");
        Admin admin=adminDao.findOne(id);
        List<AdminAuthority> adminAuthorityList=adminAuthorityDao.findByAdminId(id);
        adminAuthorityDao.delete(adminAuthorityList);//清楚此管理员 对应的权限目录列表
        adminDao.delete(admin);
          return JsonResp.ok();
    }

/*
    *//**
     * @分页查询管理员(jpa方式)
     * @param phone 账号
     * @param pageNum 第几页
     * @param pageSize 每页的条数
     * @return 返回值JsonResp
     *//*
    @RequestMapping(value = "/getAdminList",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findPageAdminJpa(String phone,String nickName,  Integer pageNum, Integer pageSize) {
        log.debug("分页查询管理员(jpa方式)");
        String sql = "FROM admin a,admin_authority b,admin_catalog c " +
                "WHERE a.status=1 AND b.status=1 AND c.status=1 AND a.id=b.admin_id AND b.catalog_id=c.id ";
        if(phone!=null && phone!=""){
            sql+=" AND a.phone="+phone;
        }
        if(nickName!=null && nickName!=""){
            sql+=" AND a.nick_name= "+nickName;
        }
        Query query = entityManager.createNativeQuery("SELECT a.id,a.phone,a.role_type,a.real_name,a.nick_name ,a.gmt_datetime ,c.catalog_name,c.catalog_url " + sql);
        BigInteger count_number = null;
        //总记录数
        Query query_number = entityManager.createNativeQuery("SELECT COUNT(1) " + sql);
        count_number = (BigInteger) query_number.getSingleResult();
        long total = count_number.longValue();
        //分页
        if ((pageNum-1) >= 0) {
            query.setFirstResult((pageNum-1) * pageSize);
        }
        if (pageSize > 0) {
            query.setMaxResults(pageSize);
        }
        entityManager.close();

        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map> mapList = new ArrayList<>();
        query.getResultList().forEach(n -> mapList.add(PubLib.copyObject(PubLib.convert(n), Map.class)));

        return JsonResp.ok(new PageDto(pageNum, pageSize, mapList, total));
    }


    */


    /**
     * @分页查询管理员(jpa方式)
     * @param phone 账号
     * @param pageNum 第几页
     * @param pageSize 每页的条数
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/getAdminList",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findPageAdminJpa(String phone,String nickName,Integer pageNum, Integer pageSize) {
        log.debug("分页查询管理员(jpa方式)");
        Sort sort = new Sort(Sort.Direction.DESC, "gmtDatetime");
        Pageable pageable = new PageRequest(pageNum - 1, pageSize, sort);
        Page page = adminDao.findAll( 		  //条件分页
                (root, criteriaQuery, cb) -> {
                    Predicate predicate = cb.conjunction();
                    List<Expression<Boolean>> expressions = predicate.getExpressions();
                    if (StringUtils.isNotBlank(nickName)) {
                        expressions.add(cb.equal(root.get("nickName"), nickName));
                    }
                    if (StringUtils.isNotBlank(phone)) {
                        expressions.add(cb.equal(root.get("phone"), phone));
                    }
                    return predicate;
                }, pageable);
           return  JsonResp.ok(new PageDto(page)) ;
    }





    /**
     * @删除管理员-one(永久)
     * @param adminId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/deleteAdminOne",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp deleteAdminOne(Long adminId) {
        log.debug("删除管理员-one(永久)");
        adminDao.delete(adminId);
        return JsonResp.ok();
    }

    /**
     * @批量删除管理员(永久)
     * @param admins
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/deleteSomeAdmin",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp deleteSomeAdmin(@RequestBody List<Admin> admins) {
        log.debug("批量删除管理员(永久)");
        adminDao.delete(admins);
        return JsonResp.ok();
    }


}
